<script setup>
import { ref, watch } from 'vue'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'

import { ExportPDF } from '@vavt/v3-extension'
import '@vavt/v3-extension/lib/asset/ExportPDF.css'

import TurndownService from 'turndown'

import MarkdownConfig from './config'

const toolbar = MarkdownConfig.toolbar

const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])

const text = ref(props.modelValue)

watch(text, () => {
  emit('update:modelValue', text.value)
})
// 粘贴的内容处理
const turndownService = new TurndownService({
  headingStyle: 'atx',
  codeBlockStyle: 'fenced',
})
const handlePaste = (event) => {
  const clipboardData = event.clipboardData || window.clipboardData
  const htmlData = clipboardData.getData('text/html')
  const plainText = clipboardData.getData('text/plain')

  if (htmlData) {
    event.preventDefault()
    const markdown = turndownService.turndown(htmlData)
    // 将内容追加或插入
    text.value = text.value.replace(plainText, `\n${markdown}\n`)
  }
}
</script>

<template>
  <MdEditor
    v-model="text"
    :showToolbarName="true"
    @onPaste="handlePaste"
    :noPrettier="true"
    :style="{ height: 'calc(100vh - 80px)' }"
    :toolbars="toolbar"
  >
    <template #defToolbars>
      <ExportPDF :modelValue="text" />
    </template>
  </MdEditor>
</template>

<style scoped lang="scss">
/* 调整 md-editor-v3 的图标样式 */
:deep(svg.md-editor-icon) {
  width: 20px;
  height: 20px;
}
/* 恢复 md-editor-v3 预览区的列表样式 */
:deep(.md-editor-preview) {
  ol li {
    list-style: decimal;
  }
  ul li {
    list-style: disc;
  }
}
</style>
